package com.android.matmanual;

//huangkai
import android.app.Activity;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.util.Log;

public class HeadsetTest extends BaseActivity {
	/** Called when the activity is first created. */
	boolean isRecording = false;
	static final int frequency = 44100;
	static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	int recBufSize, playBufSize;
	AudioRecord audioRecord;
	AudioTrack audioTrack;
	WakeLock mWakeLock;
	RecordPlayThread recordThread = null;
	HeadsetReceiver mHeadsetReceiver;
	TextView mTextView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
				"XYTEST");
		mWakeLock.acquire();
		setContentView(R.layout.headset_test);
		setTitle(R.string.headset_title);

		mTextView = (TextView) findViewById(R.id.headset_prompt_info);
		StringBuilder sb = new StringBuilder();
		sb.append("请插入耳机，留意耳机是否有周围环境噪声...\n");
		sb.append("1.有噪声-----测试OK\n");
		sb.append("2.无噪声-----测试fail");
		mTextView.setText(sb.toString());

		recBufSize = AudioRecord.getMinBufferSize(frequency,
				channelConfiguration, audioEncoding);

		playBufSize = AudioTrack.getMinBufferSize(frequency,
				channelConfiguration, audioEncoding);
		// -----------------------------------------
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
				channelConfiguration, audioEncoding, recBufSize);

		audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
				channelConfiguration, audioEncoding, playBufSize,
				AudioTrack.MODE_STREAM);
		// ------------------------------------------

		mHeadsetReceiver = new HeadsetReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.HEADSET_PLUG");
		registerReceiver(mHeadsetReceiver, intentFilter);

		isRecording = true;

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mWakeLock != null) {
			mWakeLock.release();
			mWakeLock = null;
		}
		// android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (null != recordThread) {
			recordThread.stopT();
		}

		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return true;
	}

	class RecordPlayThread extends Thread {
		public void run() {
			try {
				byte[] buffer = new byte[recBufSize];
				audioRecord.startRecording();// ��ʼ¼��

				audioTrack.play();// ��ʼ����
				while (isRecording) {
					// ��MIC������ݵ�������?
					int bufferReadResult = audioRecord.read(buffer, 0,
							recBufSize);

					byte[] tmpBuf = new byte[bufferReadResult];
					System.arraycopy(buffer, 0, tmpBuf, 0, bufferReadResult);
					// д����ݼ�����?
					audioTrack.write(tmpBuf, 0, tmpBuf.length);
					Log.v("leiyonghui", "Headset isRecording......");
				}
				audioTrack.stop();
				audioRecord.stop();
			} catch (Exception e) {
				// Toast.makeText(HeadsetTest.this, t.getMessage(), 1000);
			}
		}

		public void stopT() {
			try {
				isRecording = false;
				if (null != audioTrack) {
					audioTrack.stop();
				}
				if (null != audioRecord) {
					audioRecord.stop();
				}
			} catch (Exception e) {
				// Toast.makeText(HeadsetTest.this, t.getMessage(), 1000);
			}
		}
	};

	public class HeadsetReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("android.intent.action.HEADSET_PLUG")) {
				if (intent.hasExtra("state")) {

					if (intent.getIntExtra("state", 0) == 0) {
						Toast.makeText(HeadsetTest.this,
								getString(R.string.headset_not_insert),
								Toast.LENGTH_SHORT).show();
						if (recordThread != null) {
							recordThread.stopT();
							if (!recordThread.isInterrupted()) {
								recordThread.interrupt();
								recordThread = null;
								isRecording = false;
								if (mWakeLock != null) {
									mWakeLock.release();
									mWakeLock = null;
								}
							}
						}

					} else if (intent.getIntExtra("state", 0) == 1) {
						isRecording = true;
						if (mWakeLock == null) {
							audioTrack = new AudioTrack(
									AudioManager.STREAM_MUSIC, frequency,
									channelConfiguration, audioEncoding,
									playBufSize, AudioTrack.MODE_STREAM);
						}
						recordThread = new RecordPlayThread();
						recordThread.start();
					}
				}
			}
		}
	}

}
// end
